package com.leyou.auth.service.impl;

import com.leyou.auth.constants.JwtConstants;
import com.leyou.auth.dto.Payload;
import com.leyou.auth.dto.UserDetails;
import com.leyou.auth.service.UserAuthService;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.CookieUtils;
import com.leyou.user.client.UserClient;
import com.leyou.user.dto.UserDTO;
import feign.FeignException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.leyou.auth.constants.JwtConstants.COOKIE_NAME;
import static com.leyou.auth.constants.JwtConstants.DOMAIN;

@Service
public class UserAuthServiceImpl implements UserAuthService {

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private UserClient userClient;

    @Override
    public void login(String username, String password, HttpServletResponse response) {
        try {
            //根据用户名和密码查询用户
            UserDTO user = userClient.queryUser(username, password);
            //判断是否为空
            if (user == null) {
                //抛个异常
                throw new LyException(400, "用户名或密码错误");
            }
            //创建一个userdetail对象
            UserDetails userDetails = UserDetails.of(user.getId(), user.getUsername());
            //查询到用户，创建jwt
            String jwt = jwtUtils.createJwt(userDetails);
            //调用抽取的方法，写cookie
            writeCookie(response, jwt);
        } catch (FeignException e) {
            throw new LyException(e.status(), e.contentUTF8());
        }
    }

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response) {
        //获取cookie中的jwt
        String jwt = CookieUtils.getCookieValue(request, COOKIE_NAME);
        //判断是否有jwt
        if (StringUtils.isBlank(jwt)) {
            //没有，未登录，不用处理
            return;
        }
        try {
            //解析jwt
            Payload payload = jwtUtils.parseJwt(jwt);
            //获取用户id
            Long userId = payload.getUserDetails().getId();
            //调方法删redis中的jti
            jwtUtils.clearJti(userId);
        } catch (Exception e) {
            //报异常说明未登录，不用清理redis的数据
        }
        //删除cookie
        CookieUtils.deleteCookie(COOKIE_NAME,DOMAIN,response);
    }

    private void writeCookie(HttpServletResponse response, String jwt) {
        //新建一个cookie
        Cookie cookie = new Cookie(COOKIE_NAME, jwt);
        //设置cookie的属性
        cookie.setDomain(DOMAIN);
        cookie.setMaxAge(-1);
        cookie.setHttpOnly(true);
        cookie.setPath("/");
        //写cookie
        response.addCookie(cookie);
    }
}
